import cloud from '@lafjs/cloud'
import { setUserInfo, deleteMxyUser } from "@/thirdParty/moxueyuanUtils";
const dbm = cloud.mongo.db

let dbName = "web-users"
let data
let userId //用户ID

export default async function (ctx: FunctionContext) {
  data = { ...ctx.body.data }

  if (data.hasOwnProperty('userId')) {
    userId = data.userId
    delete data.userId
  }
  else if (cloud.utils.isString(ctx.user.uid)) {
    userId = ctx.user.uid
  } else {
    userId = ctx.user.uid._id
  }

  switch (ctx.body.type) {
    case "add":
      return add()
      break;
    case "update":
      return update()
      break;
    case "del":
      return delFunc()
      break;
    case "list":
      return list()
      break;
    case "perfect"://完善信息
      return perfect()
      break;
    case "details":
      return details()
      break;
    case "clearAll":
      return clearAll()
      break;
    case "initLogin":
      return initLogin()
      break;
    default://不分页查询
      return Search()
      break;
  }
}

async function initLogin() {
  let query = {}
  if (data.type == 1) {
    query["pc"] = {}
  } else if (data.type == 2) {
    query['wx'] = {}
  }
  let res = await dbm.collection(dbName).updateOne({
    _id: data._id
  }, {
    $set: query
  })
  return cloud.utils.requestReturn({ data: res })
}

async function clearAll() {
  await dbm.collection(dbName).deleteMany({})
  return cloud.utils.requestReturn({ data: "清空完成" })
}

async function details() {
  let res = await cloud.nw.db.findByWhereJson({
    dbName,
    whereJson: data
  });
  return cloud.utils.requestReturn({ data: res })
}

async function add() {
  await cloud.nw.db.add({
    dbName,
    dataJson: data,
    cancelAddTime: true
  });
  return cloud.utils.requestReturn({ data: "" })
}


async function list() {
  let query = { ...data }
  delete query.pageIndex
  delete query.pageSize
  delete query.studentSourceList
  delete query.tags

  query = cloud.utils.extractValidKeys(query)
  query = cloud.utils.fuzzyQuery({ ...query })
  let whereJson = {
    mobile: { $exists: true, $ne: "" },
    "baseInfo.identityCard": { $exists: true, $ne: "" },
  }
  if (data.tags && data.tags.length) {
    whereJson["baseInfo.tags"] = { $in: data.tags }
  }

  if (!cloud.utils.isEmptyObject(query)) whereJson['baseInfo'] = { ...query }
  if (data.hasOwnProperty('studentSourceList') && data.studentSourceList) {
    whereJson["baseInfo.studentSourceList.source"] = data.studentSourceList
  }

  let res = await cloud.nw.db.select({
    dbName,
    getCount: true,
    pageIndex: data.pageIndex,
    pageSize: data.pageSize,
    whereJson,
    sortArr: [
      { "name": "_add_time", "type": "desc" },
    ],
  });
  return cloud.utils.requestReturn({ data: res })
}

async function delFunc() {
  const docs = await dbm.collection('web-order')
    .find({ userId: data._id })
    .toArray()
  for (let index = 0; index < docs.length; index++) {
    const element = docs[index];
    //只要有一个不满足 状态!=已退款 || 订单最终金额!=0 就不能删除
    if (element.status == 4 && element.finalAmount == 0) {

    } else if ([6].includes(element.status)) {

    }
    else {
      return cloud.utils.requestReturn({ msg: `${element.approvalContent.model.name},有订单状态不允许删除`, code: 500 })
    }
  }
  await cloud.nw.db.del({
    dbName,
    whereJson: { _id: data._id }
  });
  deleteMxyUser(data._id)
  return cloud.utils.requestReturn({ data: "" })
}

async function update() {
  let query = { ...data }
  delete query._id
  await cloud.nw.db.update({
    dbName,
    whereJson: { _id: data._id, },
    dataJson: query
  });
  return cloud.utils.requestReturn({ data: "" })
}

async function perfect() {
  //只有姓名和手机号进行修改了，才需要执行更新魔学院
  let isContinue = false

  //要修改的值的当前值
  let res = await cloud.nw.db.findByWhereJson({
    dbName,
    whereJson: { _id: userId },
  });

  //如果手机号进行了修改，则进行唯一性判断
  if (res.mobile != data.mobile) {
    isContinue = true
    let ret = await cloud.nw.db.findByWhereJson({
      dbName,
      whereJson: { mobile: data.mobile },
    });
    if (ret && ret._id) return cloud.utils.requestReturn({ msg: "该手机号已被绑定", code: 500 })
  }

  //如果姓名进行了修改
  if (res.name != data.name) isContinue = true

  //判断身份证对应的是否是别的手机号
  let canCheckIdCard = false
  //1.之前没有维护过身份证号，现在维护了身份证号
  //2.之前维护过身份证号，现在修改了身份证号

  //如果之前都没完善过基本信息
  if (!res.hasOwnProperty("baseInfo")) {
    canCheckIdCard = true
  }
  if (!res.baseInfo.identityCard && data.identityCard) {
    canCheckIdCard = true
  } else if (res.baseInfo.identityCard != data.identityCard) {
    canCheckIdCard = true
  }
  if (canCheckIdCard) {
    let ret = await cloud.nw.db.findByWhereJson({
      dbName,
      whereJson: { baseInfo: { identityCard: data.identityCard } },
    });
    if (ret && ret._id && res.mobile != data.mobile) return cloud.utils.requestReturn({ msg: "当前身份证号已被绑定手机号", code: 500 })
  }

  if (isContinue) {
    //同步修改魔学院信息
    await setUserInfo({
      userId,
      mobile: data.mobile,
      name: data.name,
      email: data.email
    })
  }

  await cloud.nw.db.update({
    dbName,
    whereJson: { _id: userId },
    dataJson: { baseInfo: data, mobile: data.mobile }
  });
  return cloud.utils.requestReturn({ data: "" })
}

async function Search() {
  let query = { ...data }
  delete query.pageIndex
  delete query.pageSize
  delete query.studentSourceList
  delete query.tags

  query = cloud.utils.extractValidKeys(query)
  query = cloud.utils.fuzzyQuery({ ...query })
  let whereJson = {
    mobile: { $exists: true, $ne: "" },
    "baseInfo.identityCard": { $exists: true, $ne: "" },
  }
  if (data.tags && data.tags.length) {
    whereJson["baseInfo.tags"] = { $in: data.tags }
  }

  if (!cloud.utils.isEmptyObject(query)) whereJson['baseInfo'] = { ...query }
  if (data.hasOwnProperty('studentSourceList') && data.studentSourceList) {
    whereJson["baseInfo.studentSourceList.source"] = data.studentSourceList
  }
  const aa = await dbm.collection(dbName).find(whereJson).toArray()
  return cloud.utils.requestReturn({ data: aa })
}